package zuo.algo.c16;

/**
 * 在一个1-N的数组上，从s开始走，走x步，走到e有几种方法。
 */
public class RobotWalk {

    public static int walkWays1(int n, int s, int e, int k) {
        return process1(n, e, k, s);
    }

    /**
     * 00:09
     * @param n 1-N 位置对应的值
     * @param e 目的地
     * @param rest 剩余几步
     * @param cur 当前节点
     * @return 多少种方法
     */
    private static int process1(int n, int e, int rest, int cur) {
        if (rest == 0) {
            return cur == e ? 1 : 0;
        }
        if (cur == 1) {
            return process1(n, e, rest - 1, 2);
        }
        if (cur == n) {
            return process1(n, e, rest - 1, n - 1);
        }
        return process1(n, e, rest - 1, cur - 1) +
                process1(n, e, rest - 1, cur + 1);
    }

    /**
     * 00:27
     */
    public static int walkWays2(int n, int s, int e, int k) {
        int[][] dp = new int[k + 1][n + 1];
        for (int i = 0; i <= k; i++) {
            for (int j = 0; j <= n; j++) {
                dp[i][j] = -1;
            }
        }
        return process2(dp, n, e, k, s);
    }

    private static int process2(int[][] dp, int n, int e, int rest, int cur) {
        if (dp[rest][cur] != -1) {
            return dp[rest][cur];
        }
        if (rest == 0) {
            dp[rest][cur] = cur == e ? 1 : 0;
        } else if (cur == 1) {
            dp[rest][cur] = process2(dp, n, e, rest - 1, 2);
        } else if (cur == n) {
            dp[rest][cur] = process2(dp, n, e, rest - 1, n - 1);
        } else {
            dp[rest][cur] = (process2(dp, n, e, rest - 1, cur - 1)
                    + process2(dp, n, e, rest - 1, cur + 1));
        }
        return dp[rest][cur];
    }

    /**
     * 00:48
     */
    public static int walkWays3(int n, int s, int e, int k) {
        int[][] dp = new int[k + 1][n];
        for (int curr = 0; curr < n; curr++) {
            if (curr == (e - 1)) {
                dp[0][curr] = 1;
            } else {
                dp[0][curr] = 0;
            }
        }
        for (int rest = 1; rest <= k; rest++) {
            for (int curr = 0; curr < n; curr++) {
                if (curr == 0) {
                    dp[rest][curr] = dp[rest - 1][1];
                } else if (curr == (n - 1)) {
                    dp[rest][curr] = dp[rest - 1][n - 2];
                } else {
                    dp[rest][curr] = dp[rest - 1][curr - 1] + dp[rest - 1][curr + 1];
                }
            }
        }
        return dp[k][s - 1];
    }

    public static void main(String[] args) {
        System.out.println(walkWays1(5, 2, 4, 4));
        System.out.println(walkWays2(5, 2, 4, 4));
        System.out.println(walkWays3(5, 2, 4, 4));
    }
}
